package com.iemes.controller.workshop;

import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iemes.entity.InventoryFormMap;
import com.iemes.entity.MaterialAddFormMap;
import com.iemes.mapper.MaterialMapper;
import com.sun.org.apache.xpath.internal.operations.Mod;
import net.sf.json.JSONObject;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.iemes.annotation.SystemLog;
import com.iemes.controller.base.ConstantController;
import com.iemes.controller.index.BaseController;
import com.iemes.entity.ItemFormMap;
import com.iemes.entity.UserFormMap;
import com.iemes.plugin.PageView;
import com.iemes.score.GradeCalculateService;
import com.iemes.util.Common;

/**
 * 
 * @author lanyuan 2014-11-19
 * @Email: mmm333zzz520@163.com
 * @version 3.0v
 */
@Controller
@RequestMapping("/item_resource/")
public class ItemController extends BaseController {

	@Inject
	private GradeCalculateService gradeCalculateService;
	@Inject
	private MaterialMapper materialMapper;

	@RequestMapping("item_list")
	public String listUI(Model model) throws Exception {

		model.addAttribute("res", findByRes());
		return Common.BACKGROUND_PATH + "/item_resource/item/item_list";
	}

	/***
	 * 增加关联
	 */
	@RequestMapping("addAssociated")
	public String addAssociated(Model model){
		model.addAttribute("id", getPara("id"));
		return Common.BACKGROUND_PATH + "/item_resource/item/item_associated";
	}

	/**
	 * 查询原物料
	 * @param pageNow
	 * @param pageSize
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("getItemChildFindByPage")
	public PageInfo getItemChildFindByPage(String pageNow,String pageSize) throws Exception{
		//查询物料数据
		//查询原物料
//		Session session = SecurityUtils.getSubject().getSession();
		//获得物料

		if(pageNow == null){
			PageHelper.startPage(1, 10);
		}else {
			PageHelper.startPage(Integer.parseInt(pageNow), 10);
		}
		//分页
		List<InventoryFormMap> inventory = materialMapper.getInventory();
		PageInfo pageInfo = new PageInfo<>(inventory);
		return pageInfo;

//		ItemFormMap itemFormMap = new ItemFormMap();
//		itemFormMap.put("item_type", "purchase");
//		List<ItemFormMap> list = baseMapper.findByNames(itemFormMap);
//
//		pageView = getPageView(pageNow, pageSize, getPara("orderby"));
//		pageView.setQueryResult(list.size(), list);
//		return pageView;
	}
	
	/**
	 * 查询主物料
	 * @param pageNow
	 * @param pageSize
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("getItemMainFindByPage")
	public PageInfo getItemMainFindByPage(String pageNow, String pageSize, String column, String sort) throws Exception{
		if(pageNow == null){
			PageHelper.startPage(1, 10);
		}else {
			PageHelper.startPage(Integer.parseInt(pageNow), 10);
		}
		//查询主物料
//		Session session = SecurityUtils.getSubject().getSession();
//		ItemFormMap itemFormMap = new ItemFormMap();
//		itemFormMap.put("site", session.getAttribute("site").toString());
//		itemFormMap.put("item_type", "machining");
//		List<ItemFormMap> list = baseMapper.findByNames(itemFormMap);
		List<InventoryFormMap> inventory = materialMapper.getInventory();
//		pageView = getPageView(pageNow, pageSize, getPara("orderby"));
//		pageView.setQueryResult(inventory.size(), inventory);
		PageInfo pageInfo = new PageInfo<>(inventory);
		return pageInfo;
	}
	
	/**
	 * 查询所有物料
	 * @param pageNow
	 * @param pageSize
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("getItemFindByPage")
	public PageInfo getItemFindByPage(String pageNow,String pageSize) throws Exception {

//		//查询原物料
//		Session session = SecurityUtils.getSubject().getSession();
//		ItemFormMap itemFormMap = new ItemFormMap();
//		itemFormMap.put("site", session.getAttribute("site").toString());
//		//itemFormMap.put("item_type", "purchase");
//		//查询新的物料信息
//		List<InventoryFormMap> inventory = materialMapper.getInventory();
//		List<ItemFormMap> list = baseMapper.findByNames(itemFormMap);
//
//		pageView = getPageView(pageNow, pageSize, getPara("orderby"));
//		pageView.setQueryResult(inventory.size(), inventory);
//		return pageView;
		String searchForms = getPara("searchForms");
		if (searchForms == null || searchForms.equals("null") || searchForms.equals("")) {
			if (pageNow == null) {
				PageHelper.startPage(1, 10);
			} else {
				PageHelper.startPage(Integer.parseInt(pageNow), 10);
			}
			List<InventoryFormMap> inventory = materialMapper.getInventory();
			PageInfo pageInfo = new PageInfo<>(inventory);
			return pageInfo;
		} else if (searchForms.equals("0")) {
			if (pageNow == null) {
				PageHelper.startPage(1, 10);
			} else {
				PageHelper.startPage(Integer.parseInt(pageNow), 10);
			}
			List<InventoryFormMap> inventory = materialMapper.getInventory();
			PageInfo pageInfo = new PageInfo<>(inventory);
			return pageInfo;
		} else {
			if (pageNow == null) {
				PageHelper.startPage(1, 10);
			} else {
				PageHelper.startPage(Integer.parseInt(pageNow), 10);
			}
			//筛选编码前缀等于searchForms
			List<InventoryFormMap> inventory = materialMapper.getInventoryFuzzy(searchForms);
			PageInfo pageInfo = new PageInfo<>(inventory);
			return pageInfo;
		}
	}

	@ResponseBody
	@RequestMapping("item_findByPage")
	public PageInfo findByPage(String pageNow,
			String pageSize) throws Exception {
		//更改数据源
		if(pageNow == null){
			PageHelper.startPage(1, 10);
		}else {
			PageHelper.startPage(Integer.parseInt(pageNow), 10);
		}
		List<InventoryFormMap> inventory = materialMapper.getInventory();
		PageInfo pageInfo = new PageInfo<>(inventory);
		return pageInfo;
//		pageView = new PageView();
//		Session session = SecurityUtils.getSubject().getSession();
//		ItemFormMap itemFormMap = getFormMap(ItemFormMap.class);
//		itemFormMap.put("site", session.getAttribute("site"));
//		itemFormMap=toFormMap(itemFormMap, pageNow, pageSize,itemFormMap.getStr("orderby"));
//		pageView.setRecords(baseMapper.findByPage(itemFormMap));
//		return pageView;
	}

	@RequestMapping("item_addUI")
	public String addUI(Model model) throws Exception {
		return Common.BACKGROUND_PATH + "/item_resource/item/item_add";
	}

	@ResponseBody
	@RequestMapping("item_addEntity")
	//	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	@SystemLog(module="生产物料控制",methods="物料维护-新增物料")//凡需要处理业务逻辑的.都需要记录操作日志
	public String addEntity() throws Exception {

		JSONObject json = new JSONObject();

		InventoryFormMap inverntoryFormMap = getFormMap(InventoryFormMap.class);
//		Session session = SecurityUtils.getSubject().getSession();
//		// 获取request
//		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
//		// 通过工具类获取当前登录的bean
//		UserFormMap userFormMap = (UserFormMap)Common.findUserSession(request);
//		itemFormMap.put("by_user", userFormMap.getStr("accountName"));
//		itemFormMap.put("site", session.getAttribute("site"));
//
//		/*根据物料编号判断校验物料是否已经存在*/
//		String itemNo = itemFormMap.getStr("item_no");
//		List<ItemFormMap> records = baseMapper.findByAttribute("item_no", itemNo, ItemFormMap.class);
//		if(records != null && records.size() > 0){//如果新增加的物料编号存在，则提示增加报错
//			json.put("result", ConstantController.ERROR);
//			return json.toString();
//		}

		baseMapper.addEntity(inverntoryFormMap);

		String rs = null;
		try {
//			rs = gradeCalculateService.GradeCalculate("物料维护", null);
			json.put("result", ConstantController.SUCCESS);
			json.put("score", rs);
		} catch (Exception e) {
			json.put("result", ConstantController.ERROR);
		}
		return json.toString();
	}

	@RequestMapping("item_editUI")
	public String editUI(Model model) throws Exception {
		String id = getPara("id");
		if(Common.isNotEmpty(id)){
			model.addAttribute("item", baseMapper.findbyFrist("id", id, InventoryFormMap.class));
		}
		return Common.BACKGROUND_PATH + "/item_resource/item/item_edit";
	}

	@ResponseBody
	@RequestMapping("item_editEntity")
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	@SystemLog(module="生产物料控制",methods="物料维护-修改物料")//凡需要处理业务逻辑的.都需要记录操作日志
	public String editEntity() throws Exception {
		ItemFormMap itemFormMap = getFormMap(ItemFormMap.class);
		baseMapper.editEntity(itemFormMap);
		return "success";
	}

	@ResponseBody
	@RequestMapping("item_deleteEntity")
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	@SystemLog(module="生产物料控制",methods="物料维护-删除物料")//凡需要处理业务逻辑的.都需要记录操作日志
	public String deleteEntity() throws Exception {
		String[] ids = getParaValues("ids");
		for (String id : ids) {
			baseMapper.deleteByAttribute("id", id, ItemFormMap.class);
		}
		return "success";
	}

	//item_resource
	@ResponseBody
	@RequestMapping("emp_findByPage")
	public PageInfo empFindByPage(String pageNow,
							   String pageSize) throws Exception {
		String myValue = getPara("myValue");
		if(myValue == null || myValue.equals("")){
			if(pageNow == null){
				PageHelper.startPage(1, 5);
			}else {
				PageHelper.startPage(Integer.parseInt(pageNow), 5);
			}

			PageInfo pageInfo = new PageInfo<>(getEmp());
			return pageInfo;

		}else {
			String[] split = myValue.split(",");
			if(split.length > 1){
				if(split[0].equals("name")){
					//根据名称进行模糊查询
					PageInfo pageInfo = new PageInfo<>(getEmpName(split[1],"name"));
					return pageInfo;
				}else {
					//根据编号进行模糊查询
					PageInfo pageInfo = new PageInfo<>(getEmpName(split[1],"code"));
					return pageInfo;
				}
			}else {
				PageInfo pageInfo = new PageInfo<>(getEmp());
				return pageInfo;
			}
		}
	}

	//item_resource
	@ResponseBody
	@RequestMapping("client_findByPage")
	public PageInfo clientFindByPage(String pageNow,
								  String pageSize) throws Exception {


		String myValue = getPara("myValue");
		if(myValue == null || myValue.equals("")){
			if(pageNow == null){
				PageHelper.startPage(1, 5);
			}else {
				PageHelper.startPage(Integer.parseInt(pageNow), 5);
			}

			PageInfo pageInfo = new PageInfo<>(getClient());
			return pageInfo;

		}else {
			String[] split = myValue.split(",");
			if(split.length > 1){
				if(split[0].equals("name")){
					//根据名称进行模糊查询
					PageInfo pageInfo = new PageInfo<>(getClientName(split[1],"name"));
					return pageInfo;
				}else {
					//根据编号进行模糊查询
					PageInfo pageInfo = new PageInfo<>(getClientName(split[1],"code"));
					return pageInfo;
				}
			}else {
				PageInfo pageInfo = new PageInfo<>(getEmp());
				return pageInfo;
			}
		}
	}

	//关联数据
	@ResponseBody
	@RequestMapping("linkedData")
	public String linkedData(){
		//分割字符串
		String[] ids = getPara("ids").split(",");
		String materialId = getPara("id");
		//循环插入数据
		if(ids.length > 1){
			materialMapper.insertLinkData(materialId,ids[0],ids[1]);
		}else {
			materialMapper.insertLinkData(materialId,ids[0],"0");
		}
		return "success";
	}

}